package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.inventory.interfaces.IfInboundStoreRequest;
import com.sangmo.fts.process.inventory.model.IfInbound;
import com.sangmo.fts.process.inventory.model.IfLadingBillItem;
import com.sangmo.fts.process.inventory.model.IfOutbound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class IfInboundService extends DelegateViewService<IfInbound> {

    @Autowired
    private IfInboundEntityService ifInboundEntityService;

    @Autowired
    private IfLadingBillItemEntityService ifLadingBillItemEntityService;

    @Override
    protected ViewService<IfInbound> getEntityService() {
        return ifInboundEntityService;
    }

    public void receive(Long ifInboundId) {
        IfInbound inbound = this.get(ifInboundId);
        if (!IfInbound.States.DISPATCHED.equals(inbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifInbound.receive.state.wrong");
        }
        inbound.setState(IfInbound.States.PENDING);
        this.save(inbound);
    }

    public void store(Long ifInboundId, IfInboundStoreRequest request) {
        IfInbound inbound = this.get(ifInboundId);
        if (!IfInbound.States.PENDING.equals(inbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifInbound.store.state.wrong");
        }
        inbound.setCode(request.getCode());
        inbound.setState(IfInbound.States.COMPLETED);
        inbound.setInDate(request.getInDate());
        inbound.setConfirmedBy((Long)UserSession.getUserInterface().getId());
        this.save(inbound);
    }

    public PageResult<IfLadingBillItem> searchGoods(Long id, PageSearch ps) {
        IfInbound inbound = this.get(id);
        ps.getFilters().add(new ValueFilter("billId", ValueFilter.OP_EQ, inbound.getBillId()));
        return ifLadingBillItemEntityService.search(ps);
    }


}
